import {getMenuPermissionList} from '@/api/profile'
import Layout from '@/layout'
// 前端组件地图
const constantRouterComponents = {
  // 基础页面 layout 必须引入
  'Layout': Layout,


  // 你需要动态引入的页面组件

  //个人中心的组件
  'PersonalComponent': (resolve) =>  {
    require(['@/views/personal'], resolve)
  },
  'PersonalInfoComponent':(resolve) =>  {
    require(['@/views/info'], resolve)
  },
  'PersonalUpdateComponent': (resolve) =>  {
    require(['@/views/update'], resolve)
  },
  'SkillListComponent': (resolve) =>  {
    require(['@/views/skillIndex'], resolve)
  },


  // 角色管理的组件
  'RoleListComponent': (resolve) =>  {
    require(['@/views/roleList'], resolve)
  },

  // 用户管理
  'UserListComponent': (resolve) =>  {
    require(['@/views/userList'], resolve)
  },

  // 文章管理组件
  'ArticleListComponent': (resolve) =>  {
    require(['@/views/articleList'], resolve)
  },
  'WriteArticleComponent': (resolve) =>  {
    require(['@/views/writeArticle'], resolve)
  }

}

// 前端未找到页面路由（固定不用改）
const notFoundRouter = {
  path: '*', redirect: '/404', hidden: true
}


/**
 * 动态生成菜单
 * @param token
 * @returns {Promise<Router>}
 */
export const generatorDynamicRouter = () => {
  return new Promise((resolve, reject) => {
    getMenuPermissionList().then(({data}) => {
      const childrenNav = []
      //      后端数据, 根级树数组,  根级 PID
      listToTree(data, childrenNav, 0)
      const routers = generator(childrenNav)
      routers.push(notFoundRouter)
      resolve(routers)
    }).catch(err => {
      reject(err)
    })
  })
}

/**
 * 格式化树形结构数据 生成 vue-router 层级路由表
 *
 * @param routerMap
 * @param parent
 * @returns {*}
 */
export const generator = (routerMap, parent) => {
  return routerMap.map(item => {
    const {title,name,path, hidden, alwaysShow, redirect, component,icon, permission} = item || {};
    const currentRouter = {
      // 如果路由设置了 path，则作为默认 path，否则 路由地址 动态拼接生成如 /dashboard/workplace
      path: path || `${parent && parent.path || ''}/${name}`,
      // 路由名称，建议唯一
      name: name,
      // 该路由对应页面的 组件 :方案1
      // component: constantRouterComponents[item.component],
      // 该路由对应页面的 组件 :方案2 (动态加载)$`@/views/${component}`
      component: constantRouterComponents[component || name] || ((resolve) =>  {
        require([`@/views/${component}`], resolve)
      }),
      // meta: 页面标题, 菜单图标, 页面权限(供指令权限用，可去掉)
      meta: {
        title: title,
        icon: icon || undefined,
        permission: permission
      }
    }
    // 是否设置了隐藏菜单
    if (hidden) {
      currentRouter.hidden = true
    }
    // 是否设置了隐藏子菜单
    if (alwaysShow) {
      currentRouter.alwaysShow = true
    }
    // 为了防止出现后端返回结果不规范，处理有可能出现拼接出两个 反斜杠
    if (!currentRouter.path.startsWith('http')) {
      currentRouter.path = currentRouter.path.replace('//', '/')
    }
    // 重定向
    item.redirect && (currentRouter.redirect = redirect)
    // 是否有子菜单，并递归处理
    if (item.children && item.children.length > 0) {
      // Recursion
      currentRouter.children = generator(item.children, currentRouter)
    }
    return currentRouter
  })
}

/**
 * 数组转树形结构
 * @param list 源数组
 * @param tree 树
 * @param parentId 父ID
 */
const listToTree = (list, tree, parentId) => {
  list.forEach(item => {
    // 判断是否为父级菜单
    if (item.parentId === parentId) {
      const child = {
        ...item,
        key: item.key || item.name,
        children: []
      }
      // 迭代 list， 找到当前菜单相符合的所有子菜单
      listToTree(list, child.children, item.id)
      // 删掉不存在 children 值的属性
      if (child.children.length <= 0) {
        delete child.children
      }
      // 加入到树中
      tree.push(child)
    }
  })
}
